package tgc.rj.zz.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.rj.zz.custom.EasyuiResult;
import tgc.rj.zz.entity.Tbdept;
import tgc.rj.zz.form.DeptForm;
import tgc.rj.zz.service.DeptService;

@Controller
@RequestMapping("/dept")
public class DeptController {
	
	@Autowired
	private DeptService deptDAO;
	
	@RequestMapping("/manage")
	public String manager() {
		return "dept/manage";
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list() {
		List<Tbdept> list=deptDAO.findByParentIsNull();
		return list;
	}
	@RequestMapping(value="/edit")
	public void edit(Integer parentId,Integer id,ModelMap map) {
		Tbdept model=new Tbdept();
		if(id!=null) {
			model=deptDAO.findById(id);
		}
		if(parentId!=null) {
			model.setParent(deptDAO.findById(parentId));
		}
		map.put("model", model);
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(DeptForm form) {
		try {
			Tbdept model=new Tbdept();
			Integer id = form.getId();
			if(id!=null) {
				model=deptDAO.findById(id);
			}
			Integer parentId = form.getParentId();
			if(parentId!=null) {
				model.setParent(deptDAO.findById(parentId));
			}
			BeanUtils.copyProperties(form, model,"id","parent");
			deptDAO.save(model);
			return new EasyuiResult("数据保存成功");
		} catch (Exception e) {
			return new EasyuiResult(false, "数据保存失败");
		}
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(Integer id) {
		try {
			deptDAO.deleteById(id);
			return new EasyuiResult("数据删除成功");
		} catch (Exception e) {
			return new EasyuiResult(false, "数据删除失败");
		}
	}
	@RequestMapping(value="/combotree")
	@ResponseBody
	public Object combotree(Integer id,Integer nodeId) {
		List<HashMap<String, Object>> result=new ArrayList<>();
		List<Tbdept> root;
		if(id==null) {
			root = deptDAO.findByParentIsNull();
		}else {
			root=deptDAO.findByParentId(id);
		}
		for (Tbdept dept : root) {
			if(nodeId!=null&&dept.getId()==nodeId) {
				continue;
			}
			HashMap<String, Object> node=new HashMap<>();
			node.put("id", dept.getId());
			node.put("text",dept.getName());
			if(deptDAO.findByParentId(dept.getId()).size()>0) {
				node.put("state","closed");
				node.put("children",combotree(dept.getId(),nodeId));
			}
			result.add(node);
		}
		return result;
	}
}
